package xyz.yuelai.blog.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import xyz.yuelai.blog.entity.ArticleBrief;
import xyz.yuelai.blog.entity.ArticleDetail;
import xyz.yuelai.blog.service.IArticleDetailService;
import xyz.yuelai.blog.service.IArticleService;
import xyz.yuelai.blog.util.PageInfoUtil;

@Controller
public class IndexController {

	@Resource
	private IArticleService articleService;
	@Resource
	IArticleDetailService articleDetailService;

	@RequestMapping(value = { "/", "index" })
	public String index(Model model, Integer page) {
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		if (page == null || page <= 0) {
			page = 1;
		}
		pageInfoUtil.setCurrentPage(page);
		pageInfoUtil.setPageSize(13);
		List<ArticleBrief> briefs = articleService.getArticleBriefList(pageInfoUtil, new HashMap<>());
		model.addAttribute("briefs", briefs);
		model.addAttribute("page", pageInfoUtil);
		return "/index";
	}

	@RequestMapping(value = { "/detail" })
	public String detail(Model model, Integer id,HttpServletResponse resp) {
		if (id == null) {
			return "redirect:/index.html";
		}
		ArticleBrief brief = articleService.getArticleBrief(id);
		ArticleDetail detail = articleService.getArticleDetail(id);
		if (detail == null || brief == null) {
			model.addAttribute("msg", "找不到文章了");
			return "/detail";
		}
		model.addAttribute("brief", brief);
		model.addAttribute("detail", detail);
		return "/detail";
	}
}
